//
//  RMMAddNewAdressViewController.m
//  Romomo
//
//  Created by puman on 16/10/12.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMAddNewAdressViewController.h"
#import "RMMAddNewAdressView.h"
#import "RMMAdressBackView.h"
#import "RMMSelcetPickerView.h"
#import "RMMAdressDetailsViewController.h"

@interface RMMAddNewAdressViewController ()<UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@end

@implementation RMMAddNewAdressViewController
{
    RMMAdressBackView *_backView;
    RMMSelcetPickerView *_selcetPickerView;
    RMMAddNewAdressView *_addView;
    NSArray *_locationArray;
    UITextField *_nameT;
    UITextField *_mobileT;
    UITextField *_adressT;
    UITextField *_adressDetailsT;
    UITextField *_mengCardT;
    NSInteger _shenRow;
    NSInteger _shiRow;
    NSInteger _quRow;
    NSString *_shenCode;
    NSString *_shiCode;
    NSString *_regionCode;
    NSString *_msg;
    NSString *_latitude; //纬度
    NSString *_longitude; //经度
    NSString *_adress_city_name;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    [self addViews];
    // Do any additional setup after loading the view.
}
- (void)addNewAdress{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"cust_id"] = cust_id;
    parDic[@"mobile"] = _mobileT.text;
    parDic[@"add_name"] = _nameT.text;
    parDic[@"province"] = _shenCode;
    parDic[@"city"] = _shiCode;
    parDic[@"region"] = _regionCode;
    parDic[@"org_no"] = Org_no;
    parDic[@"latitude"] = _latitude.length != 0 ? _latitude : _dic[@"LATITUDE"];
    parDic[@"longitude"] = _longitude.length != 0 ? _longitude : _dic[@"LONGITUDE"];
    parDic[@"de_address"] = [NSString stringWithFormat:@"%@%@",_adressDetailsT.text,_mengCardT.text];
    if (_dic != nil) {
        parDic[@"add_id"] = _dic[@"ID"];
    }
    parDic[@"type"] = [NSString stringWithFormat:@"%d",_addView.mySwitch.isOn];
    NSString *url = GetAddAdressUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [MMProgressHUD show];
            [MMProgressHUD dismissWithSuccess:_msg title:nil afterDelay:1];
            _addNewAdressBlock();
            NS_POST(@"BIANJIDIZHI", nil, nil);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];

}
- (void)getLocationData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"code"] = @"1";
    NSString *url = LocationDataUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            _locationArray = array;
            [[RMMFileManager shareHandle] saveVale:array forKey:@"LOCATIONARRAY"];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_selcetPickerView.pickerView reloadAllComponents];
    } error:^(NSError *errors) {
        
    } view:self.view];
}

- (void)addViews{
    _addView = [[RMMAddNewAdressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_addView.showBut, showBut);
    BUTTON_S(_addView.adressBut, adressBut);
    BUTTON_S(_addView.upDataBut, upDataButClick);
    [self.view addSubview:_addView];
    for (int i = 0; i < 5; i++) {
        UITextField *textField = [self.view viewWithTag:10 + i];
        textField.delegate = self;
        if (i < 3) {
            TEXTFIELD_S(textField, textFieldChangedValue);
        }
        switch (i) {
            case 0:
                _nameT = textField;
                break;
            case 1:
            {
                _mobileT = textField;
                UIButton *but = [RMMFileManager addInputViewForTextField];
                _mobileT.keyboardType = UIKeyboardTypeNumberPad;
                _mobileT.inputAccessoryView = but;
                BUTTON_S(but, done);
            }
        
                break;
            case 2:
                _adressT = textField;
                break;
            case 3:
                _adressDetailsT = textField;
                break;
                
            case 4:
                _mengCardT = textField;
                break;
                
            default:
                break;

        }
    }
    if (_dic == nil) {
        self.navigationItem.title = @"新增地址";
        [_addView.upDataBut setTitle:@"确定新增" forState:(UIControlStateNormal)];
        _msg = @"新增成功!";
    } else {
        _msg = @"修改成功!";
        [_addView.upDataBut setTitle:@"确定修改" forState:(UIControlStateNormal)];
        self.navigationItem.title = @"编辑地址";
        _nameT.text = _dic[@"ADD_NAME"];
        _mobileT.text = _dic[@"MOBILE"];
        _adressT.text = [NSString stringWithFormat:@"%@ %@ %@",_dic[@"PROVINCE_NAME"],_dic[@"CITY_NAME"],[RMMFileManager retrunObjWith: _dic[@"REGION_NAME"]]];
        _adress_city_name = _dic[@"CITY_NAME"];
        _shenCode = _dic[@"PROVINCE"];
        _shiCode = _dic[@"CITY"];
        _regionCode = _dic[@"REGION"];
        _adressDetailsT.text = _dic[@"DE_ADDRESS"];
        [self butOpen:_addView.upDataBut];
        if ([_dic[@"TYPE"] isEqualToNumber:@0]) {
            _addView.mySwitch.on = NO;
        } else {
            _addView.mySwitch.on = YES;
        }
    }
    _selcetPickerView = [[RMMSelcetPickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_selcetPickerView.rihthBut, doneButClick);
    _selcetPickerView.pickerView.dataSource = self;
    _selcetPickerView.pickerView.delegate = self;
    _selcetPickerView.hidden = YES;
    _selcetPickerView.pickerView.backgroundColor = RGBA(237, 237, 237, 1);
    [self.view addSubview:_selcetPickerView];
    [self getLocationData];
}
- (void)done{
    [self.view endEditing:YES];
}
- (void)doneButClick{
    NSDictionary *dic = _locationArray[_shenRow];
    _shenCode = dic[@"CODE"];
    NSArray *array = dic[@"CITY"];
    NSDictionary *d = array[_shiRow];
    _shiCode = d[@"CODE"];
    NSArray *arrayQu = d[@"REGION"];
    NSDictionary *newDic = arrayQu[_quRow];
    _regionCode = newDic[@"CODE"];
    _adressT.text = [NSString stringWithFormat:@"%@ %@ %@",dic[@"NAME"],d[@"NAME"],newDic[@"NAME"]];
    _adress_city_name = d[@"NAME"];
    if ([dic[@"NAME"] isEqualToString:@"上海市"] || [dic[@"NAME"] isEqualToString:@"北京市"] || [dic[@"NAME"] isEqualToString:@"深圳市"] || [dic[@"NAME"] isEqualToString:@"天津市"] || [dic[@"NAME"] isEqualToString:@"澳门"] || [dic[@"NAME"] isEqualToString:@"香港"] || [dic[@"NAME"] isEqualToString:@"台湾"]) {
        _adress_city_name = dic[@"NAME"];
    }
    if (_mobileT.text.length > 0 && _nameT.text.length > 0 && _adressT.text.length > 0 && _adressDetailsT.text.length > 0) {
        [self butOpen:_addView.upDataBut];
    } else {
        [self butOff:_addView.upDataBut];
    }
    [UIView animateWithDuration:kInterval animations:^{
        _selcetPickerView.view.frame = CGRectMake(0, kScreenHeight , kScreenWideth, 249);
        _selcetPickerView.backView.alpha = 0.0;
    } completion:^(BOOL finished) {
        _selcetPickerView.hidden = YES;
    }];

}
- (void)textFieldChangedValue{
    if (_mobileT.text.length > 15) {
        _mobileT.text = [_mobileT.text substringToIndex:15];
        if (![RMMFileManager isPhoneNumberWith:_mobileT.text]) {
            [RMMFileManager MBProgressWith:@"手机号码错误!" onView:self.view];
        }
    }
    if (_mobileT.text.length > 0 && _nameT.text.length > 0 && _adressT.text.length > 0 && _adressDetailsT.text.length > 0) {
        [self butOpen:_addView.upDataBut];
    } else {
        [self butOff:_addView.upDataBut];
    }
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;
   // item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
    
}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)upDataButClick{
    [self.view endEditing:YES];
    [self addNewAdress];
}
- (void)showBut{
    [self.view endEditing:YES];
    if (_locationArray.count) {
        _selcetPickerView.hidden = NO;
        _selcetPickerView.type = @"location";
        [UIView animateWithDuration:kInterval animations:^{
            _selcetPickerView.view.frame = CGRectMake(0, kScreenHeight - 64 - 249, kScreenWideth, 249);
            _selcetPickerView.backView.alpha = 1.0;
        } completion:^(BOOL finished) {
        }];
    } else {
        [self getLocationData];
    }
}
- (void)adressBut{
    if (_adressT.text.length) {
        RMMAdressDetailsViewController *VC = [[RMMAdressDetailsViewController alloc] init];
        VC.delAdress = _adressDetailsT.text;
        VC.curruet_city = _adress_city_name;
        VC.blockTude = ^void (NSString *latitude, NSString *logitude, NSString *adressDetails){
            _latitude = latitude;
            _longitude = logitude;
            _adressDetailsT.text = adressDetails;
            if (_mobileT.text.length > 0 && _nameT.text.length > 0 && _adressT.text.length > 0 && _adressDetailsT.text.length > 0) {
                [self butOpen:_addView.upDataBut];
            }
        };
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        [RMMFileManager MBProgressWith:@"请先选择服务地址!" onView:self.view];
    }
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return _locationArray.count;
    } else if (component == 1) {
        NSDictionary *dic = _locationArray[_shenRow];
        NSArray *array = dic[@"CITY"];
        
        return array.count;
    } else {
        NSDictionary *dic = _locationArray[_shenRow];
        NSArray *array = dic[@"CITY"];
        NSDictionary *d = array[_shiRow];
        NSArray *arrayQu = d[@"REGION"];
        return arrayQu.count;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (_locationArray.count) {
        if (component == 0) {
            NSDictionary *dic = _locationArray[row];
            return dic[@"NAME"];
        } else if(component == 1){
            NSDictionary *dic = _locationArray[_shenRow];
            NSArray *array = dic[@"CITY"];
            NSDictionary *subDic = array[row];
            return subDic[@"NAME"];
        } else {
            NSDictionary *dic = _locationArray[_shenRow];
            NSArray *array = dic[@"CITY"];
            NSDictionary *subDic = array[_shiRow];
            NSArray *subArray = subDic[@"REGION"];
            NSDictionary *d = subArray[row];
            return d[@"NAME"];
        }
    }
    return @"";
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        _shenRow = row;
        _shiRow = 0;
        _quRow = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        });
    } else if (component == 1){
        _shiRow = row;
        _quRow = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [pickerView selectRow:0 inComponent:2 animated:YES];
        });
    } else {
        _quRow = row;
    }
    [_selcetPickerView.pickerView reloadAllComponents];
}

- (void)hidePicker:(UIButton *)button{
    [UIView animateWithDuration:kInterval animations:^{
        _backView.frame = CGRectMake(0, kScreenHeight, kScreenWideth, kScreenHeight);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)butOpen:(UIButton *)button{
    button.backgroundColor = kBasicColor;
    [button setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    button.userInteractionEnabled = YES;
}
- (void)butOff:(UIButton *)button{
    button.backgroundColor = RGBA(238, 238, 238, 1);
    [button setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
    button.userInteractionEnabled = NO;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
